package com.my.system.dao.customer;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.my.system.dao.DataBaseConnection;
import com.my.system.object.client.Account;

public class AccountDao {
	private static Connection con = null;
	private static PreparedStatement psta = null;
	private static ResultSet rs = null;
	static{
		con=DataBaseConnection.getConnection();
	}

	public static Account searchAccountByID(int id) {
		Account account = null;
		String sql = "select * from account where client_id=?";
		try {
			psta = con.prepareStatement(sql);
			psta.setInt(1, id);
			rs = psta.executeQuery();
			if (rs.next()) {
				account = new Account(rs.getInt(1), rs.getDouble(2));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			try {
				if (psta != null) {
					psta.close();
				}
				if (rs != null) {
					psta.close();
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return account;
	}

	public static boolean insertAccount(int id) {
		String sql = "insert into account values(?,?)";
		try {
			psta = con.prepareStatement(sql);
			psta.setInt(1, id);
			psta.setDouble(2, 0);
			con.setAutoCommit(false);
			int i = psta.executeUpdate();
			con.commit();
			con.setAutoCommit(true);
			if (i > 0) {
				return true;
			}
		} catch (SQLException e) {
			try {
				con.rollback();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			try {
				if (psta != null) {
					psta.close();
				}
				if (rs != null) {
					psta.close();
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		return false;
	}

	public static boolean updateBalance(Account account) {
		String sql = "update account set balance=? where client_id=?";
		try {
			psta = con.prepareStatement(sql);
			psta.setInt(2, account.getUser_id());
			psta.setDouble(1, account.getBalance());
			con.setAutoCommit(false);
			int i = psta.executeUpdate();
			con.commit();
			con.setAutoCommit(true);
			if (i > 0) {
				return true;
			}
		} catch (SQLException e) {
			try {
				con.rollback();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			try {
				if (psta != null) {
					psta.close();
				}
				if (rs != null) {
					psta.close();
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		return false;
	}
}
